package com.p7.architect.store.shoppingcart.application.command.executor;

import cn.hutool.core.collection.CollUtil;
import com.p7.architect.store.shoppingcart.application.command.UpdateItemsCommand;
import com.p7.architect.store.shoppingcart.domain.model.shoppingcart.ShoppingCart;
import com.p7.architect.store.shoppingcart.domain.model.shoppingcart.ShoppingCartId;
import com.p7.architect.store.shoppingcart.domain.model.shoppingcart.ShoppingCartRepository;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

@Slf4j
@Service
@RequiredArgsConstructor
public class UpdateItemsCommandService {

    private final ShoppingCartRepository shoppingCartRepository;

    public ShoppingCartId execute(UpdateItemsCommand command) {
        ShoppingCart shoppingCart = shoppingCartRepository.find(command.getShoppingCartId());
        if (null == shoppingCart || CollUtil.isEmpty(shoppingCart.getItems())) {
            log.info("UpdateItemsCommandService#execute shoppingCart or items is null.");
            return null;
        }
        boolean updateSuccess = shoppingCart.updateItems(command.getSkuId(), command.getItemNum());
        if (!updateSuccess) {
            return null;
        }
        shoppingCartRepository.save(shoppingCart);
        return shoppingCart.getShoppingCartId();
    }
}
